﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using UnityEngine;
using UnityEngine.Networking;

public class HttpController
{
    public static string ServerHost { get; private set; }
    private static HttpClient client { get; set; }
    
    public static string token { get; set; }

    private static Queue<RequestObj> queue = new Queue<RequestObj>();
    class RequestObj
    {
        public string api;
        public object data;
        public TaskCompletionSource<bool> wait;
    }

    /// <summary>
    /// 游戏初始化时调用
    /// </summary>
    public static void Init(string host, string _token)
    {
        ServerHost = host;
        token = _token;
        if (!ServerHost.StartsWith("http://") && !ServerHost.StartsWith("https://"))
            ServerHost = "https://" + ServerHost;
        if (ServerHost.EndsWith("/"))
            ServerHost.TrimEnd('/');
        client = new HttpClient();
        client.Timeout = 30;
    }

    public static async Task<HttpClient.Response> Get(string api, Dictionary<string, string> data)
    {
        var headers = new Dictionary<string, string>();
        if (!string.IsNullOrEmpty(token))
            headers["token"] = token;
        var url = ServerHost;
        if (!api.StartsWith("/"))
            url += "/";
        url += api;

        var req = new RequestObj
        {
            api = api,
            data = data,
            wait = new TaskCompletionSource<bool>(),
        };
        queue.Enqueue(req);
        if (queue.Count > 1)
            await req.wait.Task;
        var resp = await client.GetData(url, headers, data);
        queue.Dequeue();
        if (queue.Count > 0)
            Loom.QueueOnMainThread(() => queue.Peek().wait.SetResult(true));
        if (!resp.success)
        {
            OnHttpErrorMsg(resp.error);
        }
        return resp;
    }


    public static async Task<HttpClient.Response> Post(string api, object data)
    {
        var headers = new Dictionary<string, string>();
        if (!string.IsNullOrEmpty(token))
            headers["token"] = token;
        var url = ServerHost;
        if (!api.StartsWith("/"))
            url += "/";
        url += api;

        var req = new RequestObj
        {
            api = api,
            data = data,
            wait = new TaskCompletionSource<bool>(),
        };
        queue.Enqueue(req);
        if (queue.Count > 1)
            await req.wait.Task;
        var resp = await client.PostData(url, headers, data); 
        queue.Dequeue();
        if (queue.Count > 0)
            Loom.QueueOnMainThread(() => queue.Peek().wait.SetResult(true));
        if (!resp.success)
        {
            OnHttpErrorMsg(resp.error);
        }
        return resp;
    }

    static void OnHttpErrorMsg(string tips)
    {
        Debug.Log(tips);
    }
}
